package ntd.util.frame.spring.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;

import ntd.util.config.common.bo.ResponseBO;
import ntd.util.frame.auth.ToolLogin;
import ntd.util.util.ToolDuration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<Filter> filterRegistration(){
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
                ToolDuration.duration(() -> {
                    try {
//                    ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper(request);
//                    UtilHttp.threadLocal.set(contentCachingRequestWrapper);
//                    UtilHttp.threadLocalBody.set(ServletUtil.getBody(contentCachingRequestWrapper));

                        // token封装
                        String token = ServletUtil.getHeader(request, "ntd_token", Charset.defaultCharset());
                        ToolLogin.setToken(token);

                        filterChain.doFilter(request, response);
                    } catch (Throwable e) {
                        ServletUtil.write(response, JSONUtil.toJsonStr(new ResponseBO(500, e.getMessage())), null);
                    }
                }, StrUtil.format("接口[{}]请求", request.getRequestURI()));
            }
        });
        registration.addUrlPatterns("/*");
        registration.setOrder(0);
        return registration;
    }
}
